<template>
  <span class="ele-count-to">{{ printVal }}</span>
</template>
<script setup lang="ts">
import { computed, ref, onMounted, nextTick, defineProps } from 'vue'

const props = defineProps({
  startVal: {
    type: [Number],
    default: '',
  },
  endVal: {
    type: [Number],
    default: '',
  },
  speed: {
    type: [Number],
    default: 20,
  },
  decimals: {
    type: [Number],
    default: 0,
  },
  isReverse: {
    type: [Boolean],
    default: false,
  },
})

const start = ref(+props.startVal)
const end = ref(+props.endVal)
const formatSpeed = ref(+props.speed || 5)

const formatDecimals = computed(function () {
  let formatDecimals = props.decimals > 0 ? props.decimals : 0
  return formatDecimals
})

const decimalsLen = computed(function () {
  let decimalsLen = Math.pow(10, formatDecimals.value)
  return decimalsLen
})

const printVal = computed(function () {
  let starts = (
    start.value * decimalsLen.value / decimalsLen.value
  ).toFixed(props.decimals)
  return starts
})

const accumulativeMachine = function () {
  setTimeout(() => {
    if (props.isReverse) {
      let decimalss = formatDecimals.value === 0 ? 0 : 1 / decimalsLen.value
      let formatSpeeds = formatSpeed.value / decimalsLen.value + decimalss
      
      /// 递减怠速
      start.value = start.value - formatSpeeds
      
      if (parseInt(printVal.value) <= end.value) {
        start.value = end.value
        return
      }
    } else {
      let decimalss = formatDecimals.value === 0 ? 0 : 1 / decimalsLen.value
      let formatSpeeds = formatSpeed.value / decimalsLen.value + decimalss
      
      /// 递增怠速
      start.value = start.value + formatSpeeds
      
      if (parseInt(printVal.value) >= end.value) {
        start.value = end.value
        return
      }
    }
    accumulativeMachine()
  }, 10)
}

onMounted(function () {
  nextTick(() => {
    accumulativeMachine()
  })
})
</script>